package com.qf.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.entity.Item;
import com.qf.enums.ErrorMsgEnums;
import com.qf.exception.SsmModelException;
import com.qf.mapper.ItemMapper;
import com.qf.service.ItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
@Slf4j
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemMapper itemMapper;

    //分页查询商品信息
    @Override
    public PageInfo<Item> findPage(String name,Integer page, Integer size) {

        PageHelper.startPage(page,size);

        Example example = new Example(Item.class);
        Example.Criteria c = example.createCriteria();
        c.andLike("name","%"+name+"%");

        List<Item> list = itemMapper.selectByExample(example);

        PageInfo<Item> pageInfo = new PageInfo<>(list);

        return pageInfo;
    }

    //添加商品信息
    @Override
    @Transactional
    public void addItem(Item item) {

        int count = itemMapper.insertSelective(item);
        if (count !=1){
            log.info("【添加商品】添加商品信息失败！item={}",item);
            throw new SsmModelException(ErrorMsgEnums.ITEM_ADD_ERROR);
        }

    }

    @Override
    @Transactional
    public void del(Integer id) {
        int count = itemMapper.deleteByPrimaryKey(id);
        if (count !=1){
            log.info("【删除商品】删除商品信息失败！id={}",id);
            throw new SsmModelException(ErrorMsgEnums.ITEM_DELETE_ERROR);
        }

    }

    @Override
    public Item findById(Integer id) {
        Item item = itemMapper.selectByPrimaryKey(id);
        if (item==null){
            log.info("【查询商品】查询商品信息失败！id={}",id);
            throw new SsmModelException(ErrorMsgEnums.ITEM_SELECT_ERROR);
        }
        return item;
    }

    @Override
    @Transactional
    public void update(Item item) {
        int count = itemMapper.updateByPrimaryKeySelective(item);
        if (count !=1){
            log.info("【修改商品】修改商品信息失败！item={}",item);
            throw new SsmModelException(ErrorMsgEnums.ITEM_UPDATE_ERROR);
        }
    }


}
